package again.newlife.jackson;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;

public class JacksonTest {
    public static void main(String[] args) throws Exception {
        //1. 创建User对象
        User user = new User(1, "jack", "北京");
        //2. 获取Jackson的操作对象
        ObjectMapper mapper = new ObjectMapper();
        //3. 将user对象转为String
        String s = mapper.writeValueAsString(user);
        //4. 将user对象写入文件中
        mapper.writeValue(new FileOutputStream("day14-code/src/again/newlife/file/user.json"), user);
        //5. 将user对象写入字节数组
        byte[] bytes = mapper.writeValueAsBytes(user);
        // 6. 将json字符串：str 转为User
        User user1 = mapper.readValue(s, User.class);
        //7. 将json文件中的json字符串读入程序中并转为User
        User user2 = mapper.readValue(new FileReader("day14-code/src/again/newlife/file/user.json"), User.class);
        System.out.println(user2);
        // 8. 将字节数组bytes中的内容转化为User
        User user3 = mapper.readValue(bytes, User.class);
        System.out.println(user3);
    }
}
